import axios from '@ohos/axios';
import { util } from '@kit.ArkTS';

// 基础URL
const apiClient = axios.create({
  baseURL: 'https://api.mmp.cc/api',
  timeout: 10000, // 设置超时时间
});

// 基础URL
const apiClient1 = axios.create({
  baseURL: 'https://api.ilingku.com/int',
  timeout: 10000, // 设置超时时间
});

// 定义音乐数据接口
interface MusicData {
  id: number,
  name: string,
  singer: string,
  duration: string,
  url: string,
  pic: string,
  lrc: string
};


/**
 * 获取视频链接
 * @param type - 请求类型 (mp4/json等)
 * @param id - 类型ID
 * @returns Promise<string> 视频链接
 */
export const fetchVideoLink = async (id: string): Promise<string> => {
  try {
    const response = await apiClient.get(`/ksvideo?type=json&id=${id}`);
    if (response.status === 200 && response.data.status === 'success') {
      console.log('获取视频链接成功:', response.data.link)
      return response.data.link;
    } else {
      throw new Error('获取视频链接失败');
    }
  } catch (error) {
    console.error('请求出错:', error);
    throw error;
  }
};

//sort-->热歌榜/新歌榜/飙升榜/抖音榜/电音榜
export const getRandomMusic =
  async (sort: string): Promise<MusicData> => {
    try {
      const response = await apiClient1.get(`/v1/rand_netease?sort=${sort}&format=json`);
      if (response.status === 200) {
        console.log('--->', JSON.stringify(response.data))
        return response.data.data;
      } else {
        throw new Error('获取音乐失败');
      }
    } catch (error) {
      console.error('请求出错:', error);
      throw error;
    }
  };


export const getMusiclrc =
  async (uri: string): Promise<Uint8Array> => {
    try {
      const response = await axios.create().get(uri);
      if (response.status === 200) {
        console.log('--->', JSON.stringify(response.data))
        const textEncoder = new util.TextEncoder();
        const uint8Array = textEncoder.encode(JSON.stringify(response.data));
        return uint8Array;
      } else {
        throw new Error('获取音乐失败');
      }
    } catch (error) {
      console.error('请求出错:', error);
      throw error;
    }
  };


